<template>
    <div>
        <div class="tips border-primary j-border-radius-sm  pt-10 pb-10 pl-10 pr-20 mt-10 tipstyle">
            <!-- <i class="icon icon-tips16f j-text-main"></i> -->
            <Iconfont class="icon pt-4 pr-4" type="a-16_f_ic_about" style="color: #2d74ff;"></Iconfont>
            {{ $t('指定开启BMC服务的服务器，发送集群告警信息到BMC。') }}
        </div>

        <div class="mt-10">
            <div class="title mt6">{{ 'SNMP Trap ' + $t('通用配置') }}</div>
            <div style="width: 600px; " class="mt-22 ml-22">
                <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol"
                    :wrapper-col="wrapperCol" labelAlign="left">
                    <a-spin :spinning="loading">
                        <a-form-model-item :label="'SNMP Trap ' + $t('Version') + ':'" prop="version">
                            <a-select v-model="form.version" :placeholder="$t('Choose') + 'SNMP Trap ' + $t('版本')"
                                :getPopupContainer="(trigger) => trigger.parentNode">
                                <a-select-option v-for="item of trapversion" :value="item.value" :key="item.value">
                                    {{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                        <a-form-model-item :label="'SNMP Trap ' + $t('Mode') + ':'" prop="mode">
                            <a-select v-model="form.mode" :placeholder="$t('Choose') + 'SNMP Trap ' + $t('模式')"
                                :getPopupContainer="(trigger) => trigger.parentNode">
                                <a-select-option v-for="item of trapmode" :value="item.value" :key="item.value">
                                    {{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                        <a-form-model-item :label="'SNMP Trap ' + $t('主机标识') + ':'" prop="logotype">
                            <a-select v-model="form.logotype" :placeholder="$t('Choose') + 'SNMP Trap ' + $t('主机标识')"
                                :getPopupContainer="(trigger) => trigger.parentNode">
                                <a-select-option v-for="item of traplogotype" :value="item.value" :key="item.value">
                                    {{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                        <a-form-model-item :label="$t('团体字') + ':'" prop="character">
                            <a-input v-model="form.character" :placeholder="$t('Enter') + $t('团体字')" />
                        </a-form-model-item>
                        <a-form-model-item :label="$t('告警发送级别') + ':'" prop="alarm">
                            <a-select v-model="form.alarm" :placeholder="$t('Choose') + $t('告警发送级别')"
                                :getPopupContainer="(trigger) => trigger.parentNode">
                                <a-select-option v-for="item of alarmtype" :value="item.value" :key="item.value">
                                    {{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-spin>
                    <a-form-model-item>
                        <a-button type='primary' @click="handleSave">{{ $t('Save') }}</a-button>
                        <a-button class="ml-24" @click="handleCancel">{{ $t('Cancel') }}</a-button>
                    </a-form-model-item>
                </a-form-model>
            </div>


            <div class="title mt-24">{{ $t('接收服务器配置') }}</div>
            <div>
                <a-table class="mt-16" rowKey="id" :columns='columns' :loading="tableloading" :dataSource='dataList'
                    :locale="defaultSetting" size='small' :pagination="false">

                    <template slot="target_status" slot-scope="text, record">
                        <span>{{ statusMap.get(record.target_status) }}</span>
                    </template>


                    <template slot="address" slot-scope=" text, record ">
                        <div>
                            <a-input v-if="editKey === record.id" v-model="record.address"
                                :class="errors.address ? 'error' : ''" @input="validateAddress(record)" />
                            <span v-else>{{ text }}</span>
                        </div>
                        <div v-if="errors.address && editKey === record.id" style="color: red; font-size: 12px;">
                            {{ errors.address }}
                        </div>

                    </template>

                    <template slot="port" slot-scope="text, record">
                        <div>
                            <a-input v-if="editKey === record.id" v-model="record.port"
                                :class="errors.port ? 'error' : ''" type="number" @input="validatePort(record)" />
                            <span v-else>{{ text }}</span>
                        </div>

                        <div v-if="errors.port && editKey === record.id" style="color: red; font-size: 12px;">
                            {{ errors.port }}
                        </div>
                    </template>


                    <template slot="operate" slot-scope='text, record'>
                        <div style="display: flex;" v-userAuth="'H1-2'">
                            <span>
                                <a-switch :checked="record.target_status == 0 ? true : false"
                                    @change="hanldeStatus(record)"></a-switch>
                            </span>
                            <span class="ml-14">
                                <a v-if="editKey == record.id" @click="save(record)">{{ $t('Save') }}</a>
                                <!-- <a v-if="editKey === record.id" @click="cancelEdit(record)" class="ml-8">{{ $t('Cancel')
                                    }}</a> -->
                                <a v-else @click="edit(record)">{{ $t('Edit') }}</a>
                            </span>
                            <span class="ml-14">
                                <a @click="handleTest(record)">{{ $t('测试') }}</a>
                            </span>
                            <span class="ml-14">
                                <span @click="handleDelete(record.id)" class="j-text-red cursor-pointer"> {{
                                    $t('Delete') }}</span>
                            </span>
                        </div>
                    </template>
                </a-table>

                <div class="mt-24 mb-10">
                    <a @click="handleAddServer">{{ $t('+ 增加 Trap 服务器') }}</a>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
import EmptyData from '@/components/common/EmptyData'

export default {
    name: '',
    components: { EmptyData },
    data() {
        return {
            loading: false,
            tableloading: false,
            labelCol: { span: 6 },
            wrapperCol: { span: 18 },
            form: {
                version: '1',
                mode: '1',
                logotype: '1',
                character: 'public',
                alarm: '1',
            },
            trapversion: [
                { label: 'v2c', value: '1' },
                { label: 'v1', value: '0' },

            ],
            trapmode: [
                { label: '精准告警模式', value: '1' }

            ],
            traplogotype: [
                { label: '集群名+主机名', value: '1' },
            ],
            alarmtype: [
                { label: '提示', value: '1' },
                { label: '警告', value: '2' },
                { label: '严重', value: '3' },
            ],
            rules: {
                version: [
                    { required: true, message: this.$t('Choose') + 'SNMP Trap ' + this.$t('Version'), trigger: 'change' },
                ],
                mode: [
                    { required: true, message: this.$t('Choose') + 'SNMP Trap ' + this.$t('Mode'), trigger: 'change' },
                ],
                logotype: [
                    { required: true, message: this.$t('Choose') + this.$t('主机标识'), trigger: 'change' },
                ],
                character: [
                    { required: true, message: this.$t('Enter') + this.$t('团体字'), trigger: 'blur' },
                    { pattern: /^[a-zA-Z0-9\-\_\+\*\/\!\@\#\$\%\^\&\(\)\=\{\}\[\]\;\:\'\"\,\<\.\>\?\|`~]{1,32}$/, message: this.$t('1~32个字符，由数字、英文字母和除空格外的特殊字符组成。'), trigger: 'blur' }
                ],
                alarm: [
                    { required: true, message: this.$t('Choose') + this.$t('警发送级别'), trigger: 'change' },
                ],
            },

            defaultSetting: { emptyText: <EmptyData /> },

            statusMap: new Map([
                [0, '开启'],
                [1, '关闭']
            ]),

            switchMap: new Map([
                [0, false],
                [1, true]
            ]),

            columns: [
                { title: 'Trap' + this.$t('Server-address'), dataIndex: 'address', key: 'address', width: 180, fixed: 'left', scopedSlots: { customRender: 'address' } },
                { title: 'Trap' + this.$t('Port'), dataIndex: 'port', key: 'port', width: 180, scopedSlots: { customRender: "port" } },
                { title: this.$t('状态'), dataIndex: 'target_status', key: 'target_status', width: 80, scopedSlots: { customRender: "target_status" } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 280, fixed: 'right' }
            ],

            dataList: [],

            editKey: null, // 用来标记当前正在编辑的行
            nextId: 0,

            errors: {},
            unsavedRow: null, // 存储当前编辑但未保存的行

            originalData: {}, // 用于存储行数据的副本
        }
    },

    mounted() {
        this.getList()
        this.getSnmpList()
    },

    methods: {
        async getList() {
            const { data } = await this.$api.alarm.getSnmpTarget()
            this.tableloading = true
            if (data.flag == '0') {
                this.dataList = data.mes
                // this.tableloading = false
            }
            this.tableloading = false

        },

        async getSnmpList() {
            this.loading = true
            const { data } = await this.$api.alarm.getSnmpConfig()
            if (data.mes && Object.keys(data.mes).length !== 0) {
                    this.form.version = data.mes.trap_version,
                    this.form.mode = data.mes.tarp_model,
                    this.form.logotype = data.mes.tar_sign,
                    this.form.character = data.mes.community,
                    this.form.alarm = data.mes.grade
            }
            this.loading = false
        },
        handleSave() {
            this.$refs.ruleForm.validate(async valid => {
                if (valid) {
                    const params = {
                        trap_version: this.form.version,
                        tarp_model: this.form.mode,
                        tar_sign: this.form.logotype,
                        community: this.form.character,
                        grade: this.form.alarm,
                    }
                    this.loading = true
                    const { data } = await this.$api.alarm.saveSnmpConfig(params)
                    this.model(data.id) //返回模板
                    this.notice(data.id, data.params, data.flag) //通知列表显示                  
                    this.getSnmpList()
                    this.loading = false
                } else {
                    return false;
                }
            });
        },

        handleCancel() {
            this.getSnmpList()
            // this.$refs['ruleForm'].resetFields();
        },

        handleAddServer() {
            this.errors = {}
            // 如果当前有未保存的数据，先删除
            if (this.unsavedRow) {
                const index = this.dataList.indexOf(this.unsavedRow);
                if (index !== -1) {
                    this.dataList.splice(index, 1); // 删除未保存的数据
                }
            }
            // 在添加新行之前，恢复编辑状态下的未保存行
            if (this.editKey && this.originalData[this.editKey]) {
                const original = this.originalData[this.editKey];
                this.restoreData(original); // 恢复原始数据
            }
            const newRow = {
                id: 'new' + this.nextId++,
                address: '',
                port: '',
                target_status: 0,
            };
            this.unsavedRow = newRow; // 标记为未保存的行
            this.dataList.push(newRow);
            this.editKey = newRow.id;  // 设置为编辑状态
        },
        //进行编辑
        edit(record) {
            // 如果正在编辑其他行，恢复之前行的原始数据
            if (this.editKey && this.editKey !== record.id) {
                const original = this.originalData[this.editKey];
                if (original) {
                    this.restoreData(original); // 恢复到原始数据
                    this.errors = {}
                }
            }

            this.$set(this.originalData, record.id, { ...record });

            // 如果删除的是当前编辑行，清除编辑状态
            if (this.unsavedRow) {
                const index = this.dataList.indexOf(this.unsavedRow);
                if (index !== -1) {
                    this.dataList.splice(index, 1); // 删除未保存的数据
                }
            }

            this.editKey = record.id;
        },
        // 恢复数据到原始状态
        restoreData(originalData) {
            const row = this.dataList.find((row) => row.id === originalData.id);
            if (row) {
                row.address = originalData.address;
                row.port = originalData.port;
                row.target_status = originalData.target_status;
                this.errors = {}
            }
        },


        // // 取消编辑
        // cancelEdit(record) {
        //     console.log(record)
        //     // 恢复原始数据
        //     this.editKey = null;
        //     // 如果是新增的行，可以选择从数据列表中删除这行
        //     if (typeof (record.id) == 'number') {
        //         this.editKey = null;
        //     } else {
        //         const index = this.dataList.findIndex(item => item.id === record.id);
        //         this.dataList.splice(index, 1);
        //     }

        // },

        async hanldeStatus(record) {
            console.log("sss", this.editKey, record.id)
            if (this.editKey == record.id && typeof (record.id) == 'number') {
                record.target_status = record.target_status == 0 ? 1 : 0
            }
            else if (this.editKey == null && typeof (record.id) == 'number') {
                record.target_status = record.target_status == 0 ? 1 : 0
                const params = {
                    id: record.id,
                    address: record.address,
                    port: record.port,
                    target_status: record.target_status
                };

                const { data } = await this.$api.alarm.updateSnmpTarget(params)
                this.model(data.id) //返回模板
                this.notice(data.id, data.params, data.flag) //通知列表显示   
                if (data.flag == 0) {
                    this.getList()
                }
                this.editKey = null;
            }

            else {
                record.target_status = record.target_status == 0 ? 1 : 0
                // const params = {
                //     address: record.address,
                //     port: record.port,
                //     target_status: 0
                // };

                // const { data } = this.$api.alarm.addSnmpTarget(params)
                // console.log("add", data)
                // this.getList()
                // this.editKey = null;
            }
            // console.log("sytatusval", record)
        },

        async save(record) {
            // 清空之前的错误信息
            this.errors = {};
            // 校验字段
            let valid = true;
            // 验证地址字段
            if (!record.address) {
                this.errors.address = '地址不能为空';
                valid = false;
            } else if (!this.isValidAddress(record.address)) {
                this.errors.address = '请输入正确的IP地址';
                valid = false;
            }
            // 验证端口字段
            if (!record.port) {
                this.errors.port = '端口不能为空';
                valid = false;
            } else if (record.port < 1 || record.port > 65535) {
                this.errors.port = '端口号必须在 1 和 65535 之间';
                valid = false;
            }
            // 如果表单验证通过
            if (valid) {
                console.log("表单验证通过，保存数据", record);

                if (typeof (record.id) == 'number') {
                    const params = {
                        id: record.id,
                        address: record.address,
                        port: record.port,
                        target_status: record.target_status
                    };

                    const { data } = await this.$api.alarm.updateSnmpTarget(params)
                    this.model(data.id) //返回模板
                    this.notice(data.id, data.params, data.flag) //通知列表显示  
                    if (data.flag == 0) {
                        this.getList()
                    }
                    this.editKey = null;

                } else {
                    const params = {
                        address: record.address,
                        port: record.port,
                        target_status: record.target_status
                    };

                    const { data } = await this.$api.alarm.addSnmpTarget(params)
                    this.model(data.id) //返回模板
                    this.notice(data.id, data.params, data.flag) //通知列表显示   
                    if (data.flag == 0) {
                        this.getList()
                    }
                    this.editKey = null;

                }

            } else {
                console.log("表单验证失败");
            }

        },

        // 校验地址格式
        isValidAddress(address) {
            const ipPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
            return ipPattern.test(address);
        },
        validateAddress(record) {
            const ipPattern = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
            if (!record.address || record.address.trim() === '') {
                this.errors.address = '地址不能为空';
            } else if (!ipPattern.test(record.address)) {
                this.errors.address = '请输入正确的IP地址';
            } else {
                this.errors.address = '';  // 清除错误
            }
        },
        validatePort(record) {
            const port = record.port;
            if (!port || port === '') {
                this.errors.port = '端口不能为空';
            } else if (!/^\d+$/.test(port)) {  // 检查是否为数字
                this.errors.port = '端口只能是数字';
            } else if (parseInt(port) < 1 || parseInt(port) > 65535) {
                this.errors.port = '端口号必须在 1 和 65535 之间';
            } else {
                this.errors.port = '';  // 清除错误
            }
        },

        async handleTest(item) {
            const params = {
                ipaddr: item.address,
                port: item.port
            }
            const { data } = await this.$api.alarm.checkSnmp(params)
            this.model(data.id) //返回模板
            this.notice(data.id, data.params, data.flag) //通知列表显示 
        },

        async handleDelete(id) {
            // 如果删除的是当前编辑行，清除编辑状态
            if (this.unsavedRow) {
                const index = this.dataList.indexOf(this.unsavedRow);
                if (index !== -1) {
                    this.dataList.splice(index, 1); // 删除未保存的数据
                }
            }
            if (typeof (id) == 'number') {
                this.tableloading = true
                const { data } = await this.$api.alarm.delSnmpTarget({ id })
                this.model(data.id) //返回模板
                this.notice(data.id, data.params, data.flag) //通知列表显示
                this.getList()
                this.tableloading = false

                const index = this.dataList.findIndex(item => item.id === id);
                if (index !== -1) {
                    this.dataList.splice(index, 1);
                }
                this.loading = false
            }

        },


    }
}
</script>

<style scoped>
.title {
    border-left: 3px solid #3590eb;
    padding-left: 8px;
    font-weight: bold;
    font-size: 16px;
    color: #333333;
}

.tipstyle {
    background-color: #cad5ff;
    border-color: #8ca3ff;
}

.error {
    border: 1px solid red !important;
    /* box-shadow: 0 0 0 rgb(212, 2, 2) !important; */
}

:deep(.ant-table-tbody > tr > td) {
    /* padding: 16px !important */
}
</style>